Temporary download link is extremely helpful to offer Digital products on the site. It gives a safe method to share the download link of the advanced items. The client permits downloading the record just a single time, after the download the link is terminated or evacuated. The one-time download link is perfect to give an advanced item (code, music, video, and so on) to a solitary individual and terminate the link once the item is downloaded.
With the single-utilize download link, you don’t have to physically screen the download action keeping in mind the end goal to change the download link. Rather, the download link will be terminated quickly after the primary download. In this instructional exercise, we will demonstrate to you proper methodologies to produce one-time download link in PHP and execute the temporary download URL usefulness on the web application utilizing PHP.
The illustration code enables you to create a one of a kind link to download the document from the server. This link will enable the client to download one time. Likewise, the link will have a termination time and it will be lapsed after the predefined expiry date.
For instance, you need to offer an eBook on your site. The eBook is sold on your site for $5, you could utilize our content to enable that client to download the separate eBook just a single time. The download link will give them a predetermined number of seconds/minutes/hours/days/week/years to assert their download.
The following procedure will be taken to implement the temporary download link functionality in PHP.
- Create a download link with a special key.
- Make a secured directory to store keys.
- Make a file and write a one of a unique key to it.
- On download ask for, token key and lapse time is approved.
- Power the program to download the record.
Setups (config.php)
The setup factors are characterized in this document.
- $files – A variety of the records with the one of a kind ID.
- You can indicate the distinctive name of the record being downloaded. It secures the first document.
- You can determine the nearby or remote record way.
- BASE_URL – Define the URL of the application.
- DOWNLOAD_PATH – Define the way of the document downloading content.
- TOKEN_DIR – Set the token directory way where the keys will be put away.
- OAUTH_PASSWORD – Set the verification secret word to produce a download link.
- EXPIRATION_TIME – Set a period when the document will terminate.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php // Array of the files with an unique ID $files = array( 'UID54321' => array( 'content_type' => 'application/zip', 'suggested_name' => 'tutorials-file.zip', 'file_path' => 'files/test.zip', 'type' => 'local_file' ), 'UID09876' => array( 'content_type' => 'audio/mpeg', 'suggested_name' => 'tune-tutorials.mp3', 'file_path' => 'https://www.dropbox.com/XXXXXXX/video.mp3?dl=1', 'type' => 'remote_file' ), ); // Base URL of the application define('BASE_URL','http://'. $_SERVER['HTTP_HOST'].'/'); // Path of the download-link.php file define('DOWNLOAD_PATH', BASE_URL.'download-link.php'); // Path of the token directory to store keys define('TOKEN_DIR', 'tokens'); // Authentication password to generate download links define('OAUTH_PASSWORD','Tutorialswebsite'); // Expiration time of the link (examples: +1 year, +1 month, +5 days, +10 hours) define('EXPIRATION_TIME', '+5 minutes'); |
index.php
In this document, a link will be shown to explore to the download link creation record. The confirmation secret key should be indicated in the inquiry string of the link.
2 3 4 |
<a href="generate-link.php?Tutorialswebsite">Generate download link</a> |
Make Temporary Download Link (generate-link.php)
This document makes a temporary download link and records the links on the page. The inquiry string must have the verification watchword and should be coordinated with the predefined in the config.php document, generally, 404 mistake is rendered.
- Get the validation secret word from the question string.
- Approve the validation secret word.
- Encode the record ID with base64_encode() in PHP.
- Produce another interesting key with a timestamp utilizing uniqid() in PHP.
- Create download link with record ID and key.
- Make a secured directory to store keys.
- Write the key in a record and place it in the token directory.
- List all the download links in the page.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<?php // Include the configuration file require_once 'config.php'; // Grab the password from the query string $oauthPass = trim($_SERVER['QUERY_STRING']); // Verify the oauth password if($oauthPass != OAUTH_PASSWORD){ // Return 404 error, if not a correct path header("HTTP/1.0 404 Not Found"); exit; }else{ // Create a list of links to display the download files $download_links = array(); // If the files exist if(is_array($files)){ foreach($files as $fid => $file){ // Encode the file ID $fid = base64_encode($fid); // Generate new unique key $key = uniqid(time().'-key',TRUE); // Generate download link $download_link = DOWNLOAD_PATH."?fid=$fid&key=".$key; // Add download link to the list $download_links[] = array( 'link' => $download_link ); // Create a protected directory to store keys if(!is_dir(TOKEN_DIR)) { mkdir(TOKEN_DIR); $file = fopen(TOKEN_DIR.'/.htaccess','w'); fwrite($file,"Order allow,deny\nDeny from all"); fclose($file); } // Write the key to the keys list $file = fopen(TOKEN_DIR.'/keys','a'); fwrite($file, "{$key}\n"); fclose($file); } } } ?> <!-- List all the download links --> <?php if(!empty($download_links)){ ?> <ul> <?php foreach($download_links as $download){ ?> <li><a href="<?php echo $download['link']; ?>"><?php echo $download['link']; ?></a></li> <?php } ?> </ul> <?php }else{ ?> <p>Links are not found...</p> <?php } ?> |
Download File by Temporary Link (download-link.php)
This document downloads the record by the temporary download link.
- Get the document ID and key from the question string of the URL.
- Get the time from the key and figure link termination time.
- Recover the keys from the tokens record.
- Circle through the keys to discover a match, when the match is discovered, evacuate it.
- Put the rest of the keys again into the tokens record.
- if match found and the link isn’t expired
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
<?php // Include the configuration file require_once 'config.php'; // Get the file ID & key from the URL $fid = base64_decode(trim($_GET['fid'])); $key = trim($_GET['key']); // Calculate link expiration time $currentTime = time(); $keyTime = explode('-',$key); $expTime = strtotime(EXPIRATION_TIME, $keyTime[0]); // Retrieve the keys from the tokens file $keys = file(TOKEN_DIR.'/keys'); $match = false; // Loop through the keys to find a match // When the match is found, remove it foreach($keys as &$one){ if(rtrim($one)==$key){ $match = true; $one = ''; } } // Put the remaining keys back into the tokens file file_put_contents(TOKEN_DIR.'/keys',$keys); // If match found and the link is not expired if($match !== false && $currentTime <= $expTime){ // If the file is found in the file's array if(!empty($files[$fid])){ // Get the file data $contentType = $files[$fid]['content_type']; $fileName = $files[$fid]['suggested_name']; $filePath = $files[$fid]['file_path']; // Force the browser to download the file if($files[$fid]['type'] == 'remote_file'){ $file = fopen($filePath, 'r'); header("Content-Type:text/plain"); header("Content-Disposition: attachment; filename=\"{$fileName}\""); fpassthru($file); }else{ header("Content-Description: File Transfer"); header("Content-type: {$contentType}"); header("Content-Disposition: attachment; filename=\"{$fileName}\""); header("Content-Length: " . filesize($filePath)); header('Pragma: public'); header("Expires: 0"); readfile($filePath); } exit; }else{ $response = 'Download link is not valid.'; } }else{ // If the file has been downloaded already or time expired $response = 'Download link is expired.'; } ?> <html> <head> <title><?php echo $response; ?></title> </head> <body> <h1><?php echo $response; ?></h1> </body> </html> |
Conclusion
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request
[sociallocker]
[/sociallocker]
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co